/*
 * @(#)OfflineTaskDbChange.java   1.0  2021年12月9日
 * 
 * Copyright (c)	2014-2020. All Rights Reserved.	GuangZhou hhmk Technology Company LTD.
 */
package com.swift.dts.init;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.swift.core.env.ConfigInterface.ChangeConfigKV;
import com.swift.core.env.ConfigInterface.ConfigChangeListener;
import com.swift.dts.dao.DbConfigDao;
import com.swift.dts.dao.OfflineStateInfoDao;
import com.swift.dts.dao.model.OfflineStateInfo;
import com.swift.dts.init.core.DbChange;
import com.swift.dts.loadconfig.model.DtsDataBase;
import com.swift.dts.offline.OfflineLifeCycle;
import com.swift.util.type.TypeUtil;

/**
 * 添加说明 
 * @author zhengjiajin
 * @version 1.0 2021年12月9日
 */
@Component
@Order(2)
public class OfflineTaskDbChange extends DbChange implements ConfigChangeListener<DtsDataBase> {

    @Autowired
    private OfflineLifeCycle offlineLifeCycle;
    
    @Autowired
    private DbConfigDao dbConfigDao;
    
    @Autowired
    private OfflineStateInfoDao offlineStateInfoDao;
    /** 
     * @see com.swift.core.env.ConfigInterface.ConfigChangeListener#listener(java.util.List)
     */
    @Override
    public void listener(List<ChangeConfigKV<DtsDataBase>> list) {
        this.onListener(list);
    }
    
    @Override
    public void onAdd(DtsDataBase t) {
        if(t.getIsSource()) {
            List<DtsDataBase> slaveList = dbConfigDao.slaveList();
            if(TypeUtil.isNull(slaveList)) return;
            for(DtsDataBase slave:slaveList) {
                offlineLifeCycle.startOfflineTash(t.getKey(), slave.getKey());
            }
        } else {
            List<DtsDataBase> sourceList = dbConfigDao.sourceList();
            if(TypeUtil.isNull(sourceList)) return;
            for(DtsDataBase source:sourceList) {
                offlineLifeCycle.startOfflineTash(source.getKey(), t.getKey());
            }
        }
    }

    @Override
    public void onDelete(DtsDataBase t) {
        List<OfflineStateInfo> list = offlineStateInfoDao.list();
        if(TypeUtil.isNull(list)) return;
        for(OfflineStateInfo info:list) {
            if(t.getIsSource()) {
                if(!t.getKey().equalsIgnoreCase(info.getDataSource())) continue;
            } else {
                if(!t.getKey().equalsIgnoreCase(info.getDestination())) continue;
            }
            offlineLifeCycle.delete(info);
        }
    }

    @Override
    public void onModify(DtsDataBase old,DtsDataBase ne) {
        if(!checkAddressChange(old, ne) && !checkSourceChange(old, ne)) return;
        onDelete(old);
        onAdd(ne);
    }

}
